﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using General.Core.Data;
using General.Entities.Models;
using General.Entities.ViewData.Chat;
using General.Entities.ViewData.Customer;
using General.Entities.ViewData.SystemConfig;
using General.Framework;
using General.Mvc.Filters;
using General.Services.Admin;
using General.Services.SystemConfig;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace General.Mvc.Controllers
{
    [Route("api/app/v1/customer/[action]")]
    [ApiController]
    [ServiceFilter(typeof(ResponseLogTimeFilter))]
    public class CustomerController : Controller
    {
        private readonly IAdminService adminService;
        private readonly ISystemConfigService systemConfigService;
        private readonly IRepository<tc_user> tc_UserRepository;
        private readonly IRepository<tc_admin> tc_AdminRepository;
        private readonly IRepository<tc_message> tc_MessageRepository;
        private readonly IRepository<tc_sysconfig> tc_SysconfigRepository;
        private readonly ILogger<CustomerController> logger;

        public CustomerController(IAdminService adminService,
            ISystemConfigService systemConfigService,
            IRepository<tc_user> tc_userRepository,
             IRepository<tc_admin> tc_adminRepository,
             IRepository<tc_sysconfig> tc_sysconfigRepository,
              IRepository<tc_message> tc_messageRepository,
            ILogger<CustomerController> logger)
        {
            this.adminService = adminService;
            this.systemConfigService = systemConfigService;
            tc_UserRepository = tc_userRepository;
            tc_AdminRepository = tc_adminRepository;
            tc_MessageRepository = tc_messageRepository;
            tc_SysconfigRepository = tc_sysconfigRepository;
            this.logger = logger;
        }


        /// <summary>
        /// 登录处理方法
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        /// <param name="CaptchaCode"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login([FromForm] string username, [FromForm] string password)
        {
            AjaxResult result = new AjaxResult();
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "账号或密码不能为空！";
                return Content(JsonHelper.Serialize(result));
            }
            var user = await adminService.GetInfoByLoginName(username);
            if (user == null)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "不存在此账户！";
                return Content(JsonHelper.Serialize(result));
            }
            var ip = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Connection.RemoteIpAddress.ToString();
            }
            if (user.password != EncryptHelper.Md5(password))
            {
                logger.LogInformation(new Exception("客服端登录失败"), "ip:" + ip + " 用户名:" + username + " 密码:" + password);
                result.code = AjaxResultStateEnum.Error;
                result.message = "密码错误！";
                return Content(JsonHelper.Serialize(result));
            }
            if (user.status != 1)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "您被禁止登录！";
                return Content(JsonHelper.Serialize(result));
            }

            logger.LogInformation(new Exception("客服端登录成功"), "ip:" + ip + " 用户名:" + username + " 密码:" + password);
            //更新最后登录信息
            await adminService.UpdateLoginStatusInfo(user.id, ip);

            var token = Guid.NewGuid().ToString();
            await RedisHelper.SetAsync("customertoken" + token, user.id.ToString(), 60 * 60 * 24 * 7); //保存7天
            result.code = AjaxResultStateEnum.Ok;
            result.data = token;
            result.message = "登录成功！";
            return Content(JsonHelper.Serialize(result));
        }

        /// <summary>
        /// 判断是否登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> LoginInfo()
        {
            return Content(new AjaxResult().Ok("logined"));
        }


        /// <summary>
        /// 客服获取个人信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> GetInfo()
        {
            AjaxResult result = new AjaxResult();
            CustomerInfo model = new CustomerInfo();

            var auth = HttpContext.Request.Headers["Auth"].ToString();
            var userid = await RedisHelper.GetAsync("customertoken" + auth);
            var admin = await adminService.GetInfoById(Convert.ToInt32(userid));

            model.id = admin.id;
            model.img = admin.headimg;
            model.username = admin.username;

            result.code = AjaxResultStateEnum.Ok;
            result.data = model;
            return Content(JsonHelper.Serialize(result));
        }


        /// <summary>
        /// 客服编辑个人信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> EditInfo([FromForm]string username,[FromForm]string img)
        {
            AjaxResult result = new AjaxResult();
            var auth = HttpContext.Request.Headers["Auth"].ToString();
            var userid = await RedisHelper.GetAsync("customertoken" + auth);
            var admin = await adminService.GetInfoById(Convert.ToInt32(userid));
            admin.headimg = img;
            admin.username = username;
            await tc_AdminRepository.UpdateAsync(admin);
            return Content(result.Ok("修改成功"));
        }

        /// <summary>
        /// 获取系统配置信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="img"></param>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> GetSystemConfig()
        {
            AjaxResult result = new AjaxResult();
            CustomerConfigModel model = new CustomerConfigModel();
            var configList = await systemConfigService.GetAllConfigInfo();
            model.helloContent = configList.Where(x=>x.code == nameof(model.helloContent)).FirstOrDefault().value;
            model.maxuploadbyte = configList.Where(x => x.code == nameof(model.maxuploadbyte)).FirstOrDefault().value;
            model.offlineTip = configList.Where(x => x.code == nameof(model.offlineTip)).FirstOrDefault().value;
            model.recordcount = configList.Where(x => x.code == nameof(model.recordcount)).FirstOrDefault().value;
            model.showHello = configList.Where(x => x.code == nameof(model.showHello)).FirstOrDefault().value;
            model.showOfflineTip = configList.Where(x => x.code == nameof(model.showOfflineTip)).FirstOrDefault().value;
            model.usersavetime = configList.Where(x => x.code == nameof(model.usersavetime)).FirstOrDefault().value;

            result.data = model;
            result.code = AjaxResultStateEnum.Ok;
            return Content(JsonHelper.Serialize(result));
        }


        /// <summary>
        /// 设置系统配置信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="img"></param>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> SetSystemConfig([FromForm]CustomerConfigModel model)
        {
            AjaxResult result = new AjaxResult();
            var configList = await tc_SysconfigRepository.Table.Where(x=>true).ToListAsync();
            configList.Where(x=>x.code == nameof(model.helloContent)).FirstOrDefault().value = model.helloContent;
            configList.Where(x => x.code == nameof(model.maxuploadbyte)).FirstOrDefault().value = model.maxuploadbyte;
            configList.Where(x => x.code == nameof(model.offlineTip)).FirstOrDefault().value = model.offlineTip;
            configList.Where(x => x.code == nameof(model.recordcount)).FirstOrDefault().value = model.recordcount;
            configList.Where(x => x.code == nameof(model.showHello)).FirstOrDefault().value = model.showHello;
            configList.Where(x => x.code == nameof(model.showOfflineTip)).FirstOrDefault().value = model.showOfflineTip;
            configList.Where(x => x.code == nameof(model.usersavetime)).FirstOrDefault().value = model.usersavetime;
            await tc_SysconfigRepository.UpdateListAsync(configList);
            result.message = "修改成功";
            result.code = AjaxResultStateEnum.Ok;
            return Content(JsonHelper.Serialize(result));
        }

        /// <summary>
        /// 获取所有记录数
        /// </summary>
        /// <param name="environment"></param>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> GetAllRecord()
        {
            AjaxResult result = new AjaxResult();
            CustomerRecordModel model = new CustomerRecordModel();
            model.messagecount = await tc_MessageRepository.CountAsync();
            model.usercount = await tc_UserRepository.CountAsync();

            result.code = AjaxResultStateEnum.Ok;
            result.message = "success";
            result.data = model;
            return Content(JsonHelper.Serialize(result));
        }

        /// <summary>
        /// 清空所有用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> ClearAllUser()
        {
            await tc_UserRepository.ExecuteSqlAsync("delete from tc_user");
            var keys = RedisHelper.Keys("token" + "*");
            await RedisHelper.DelAsync(keys);
            //var keys2 = RedisHelper.Keys("uid-ConnectionId-" + "*");
            //await RedisHelper.DelAsync(keys2);
            return Content(new AjaxResult().Ok("清空成功"));
        }

        /// <summary>
        /// 清空所有聊天记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> ClearAllMessage()
        {
            await tc_MessageRepository.ExecuteSqlAsync("delete from tc_message");
            return Content(new AjaxResult().Ok("清空成功"));
        }

        /// <summary>
        /// 清空所有上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> ClearAllUploadFiles([FromServices] IWebHostEnvironment environment)
        {
            string webRootPath = environment.WebRootPath;
            if (System.IO.Directory.Exists(webRootPath + "/upload/photo"))
            {
                try
                {
                    System.IO.Directory.Delete(webRootPath + "/upload/photo", true);
                }
                catch (System.IO.IOException e)
                {
                    logger.LogError("ClearAllUploadFiles删除文件夹失败！", e);
                }
            }

            return Content(new AjaxResult().Ok("清空成功"));
        }


        /// <summary>
        /// 修改登录密码
        /// </summary>
        /// <param name="environment"></param>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> UpdatePwd([FromForm]string newpwd)
        {
            AjaxResult result = new AjaxResult();
            if (string.IsNullOrEmpty(newpwd))
            {
                return Content(result.Error("新密码长度不能为空"));
            }
            await adminService.UpdateUserPwd(1,newpwd);
            return Content(result.Ok("修改成功"));
        }


        /// <summary>
        /// 客服上传头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> UploadAvatar([FromServices] IWebHostEnvironment environment)
        {
            AjaxResult state = new AjaxResult();
            string path = string.Empty;
            var files = Request.Form.Files.Where(c => c.Name == "file");
            if (files == null || files.Count() <= 0) { state.code = 0; state.message = "请选择上传的文件。"; return Json(state); }
            string webRootPath = environment.WebRootPath;
            var Month = DateTime.Now.Month.ToString();
            var Day = DateTime.Now.Day.ToString();
            string timedir = "/" + DateTime.Now.Year + "/" + (Month.Length == 1 ? "0" + Month : Month) + "/" + (Day.Length == 1 ? "0" + Day : Day) + "/";
            if (!Directory.Exists(webRootPath + "/upload" + timedir))
            {
                Directory.CreateDirectory(webRootPath + "/upload" + timedir);
            }
            var filename = files.FirstOrDefault().FileName;
            if (System.IO.File.Exists(webRootPath + "/upload" + timedir + filename))
            {
                var guid = Guid.NewGuid();
                filename = guid + Path.GetExtension(files.FirstOrDefault().FileName);
            }
            string strpath = Path.Combine("upload" + timedir, filename);

            path = Path.Combine(webRootPath, strpath);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                await files.FirstOrDefault().CopyToAsync(stream);
            }

            state.code = AjaxResultStateEnum.Ok;
            state.message = "上传成功";
            state.data = "/" + strpath;
            return Json(state);
        }

        /// <summary>
        /// 客服上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> UploadPhoto([FromServices] IWebHostEnvironment environment)
        {
            AjaxResult state = new AjaxResult();
            string path = string.Empty;
            var files = Request.Form.Files.Where(c => c.Name == "file");
            if (files == null || files.Count() <= 0) { state.code = 0; state.message = "请选择上传的文件。"; return Json(state); }
            string webRootPath = environment.WebRootPath;
            var Month = DateTime.Now.Month.ToString();
            var Day = DateTime.Now.Day.ToString();
            string timedir = "/" + DateTime.Now.Year + "/" + (Month.Length == 1 ? "0" + Month : Month) + "/" + (Day.Length == 1 ? "0" + Day : Day) + "/";
            if (!Directory.Exists(webRootPath + "/upload/photo" + timedir))
            {
                Directory.CreateDirectory(webRootPath + "/upload/photo" + timedir);
            }
            var filename = files.FirstOrDefault().FileName;
            if (System.IO.File.Exists(webRootPath + "/upload/photo" + timedir + filename))
            {
                var guid = Guid.NewGuid();
                filename = guid + Path.GetExtension(files.FirstOrDefault().FileName);
            }
            string strpath = Path.Combine("upload/photo" + timedir, filename);

            path = Path.Combine(webRootPath, strpath);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                await files.FirstOrDefault().CopyToAsync(stream);
            }

            state.code = AjaxResultStateEnum.Ok;
            state.message = "上传成功";
            state.data = "/" + strpath;
            return Json(state);
        }


        /// <summary>
        /// 创建聊天用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
       // [CustomerCheckFilter]
        public async Task<IActionResult> CreateSignalR()
        {
            AjaxResult result = new AjaxResult();
            string token = HttpContext.Request.Headers["Auth"].ToString();
            var customerid = await RedisHelper.GetAsync("customertoken" + token);
            var savedaymodel = await systemConfigService.GetConfigInfoByCode("usersavetime");
            var savedayval = Convert.ToInt32(savedaymodel.value);
            if (string.IsNullOrEmpty(customerid))
            {
                return Content(result.Error("未登录"));
            }
            //配置及时通讯
            var claims = new[]
            {
                    new Claim("customerid", customerid),
                    new Claim("token",token),
                    new Claim("isadmin","1")
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSettings.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwttoken = new JwtSecurityToken(JwtSettings.Issuer,
               JwtSettings.Audience, claims,
               expires: DateTime.Now.AddDays(savedayval),
               signingCredentials: creds);
            //约等于明文保存的 claims+签名
            string access_token = new JwtSecurityTokenHandler().WriteToken(jwttoken);
            result.message = token;
            result.data = access_token;
            result.code = AjaxResultStateEnum.Ok;
            return Content(JsonHelper.Serialize(result));
        }


        /// <summary>
        /// 获取聊天群组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CustomerCheckFilter]
        public async Task<IActionResult> GetGroupInfo([FromForm]int uid)
        {
            AjaxResult result = new AjaxResult();
            ClientGroupModel model = new ClientGroupModel();
            model.chatid = uid.ToString();
            //获取管理员信息
            var admin = await adminService.GetInfoById(1);
            //获取用户信息
            var user = await tc_UserRepository.getByIdAsync(uid);
            model.chatname = user.username;
            model.chatuser = new List<string>()
            {
                admin.headimg,user.userimg
            };

            return Content(JsonHelper.Serialize(model));
        }


    }
}
